import json

from django.shortcuts import render,redirect
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from apps.comments.models import Comment
from django.views import View
from django.http import JsonResponse
from apps.users.views import LoginRequiredJsonMixin
class update_comment(View):
  def post(self,request):
    data = json.loads(request.body.decode())
    try:
      user=request.user
      text = data.get('text')
      content_type = data.get('content_type')
      object_id = int(data.get('object_id'))
      model_class = ContentType.objects.get(model=content_type).model_class()
      model_obj = model_class.objects.get(pk=object_id)
      comment = Comment()
      comment.user = user
      comment.text = text
      comment.content_object = model_obj
      comment.save()
      return JsonResponse({'code': 0, 'errmsg': '提交评论成功'})
    except:
      return JsonResponse({'code':400,'errmsg':'登录后可发表信息'})
  def get(self,request):
    content_type = request.GET.get('content_type')
    object_id = request.GET.get('object_id')
    model_class = ContentType.objects.get(model=content_type)
    comments=Comment.objects.filter(content_type=model_class,object_id=object_id,parent=None)
    comment_list=[]
    comment_count=comments.count()
    for item in comments:
      comment_list.append({
        'comment_time':item.comment_time,
        'comment_text':item.text,
        'username':item.user.username,
        'nickname':item.user.nickname,
        'img_header':str(item.user.img_header)

      })
    return JsonResponse({'code':0,'errmsg':'获取评论列表成功','comment_list':comment_list,'count':comment_count})
    # comments=Comment.objects.filter(content_type=content_type,object_id=object_id,parent=None)
    # model_obj = model_class.objects.get(pk=29)
    # comments=Comment.objects.filter(content_type='forum')
 # model_obj=model_class.objects.get(pk=29)

from django.shortcuts import render

# Create your views here.
